import 'package:get/get.dart';
import '../models/device_model.dart';
import '../repositories/device_repository.dart';
import 'package:flutter/foundation.dart';

/// 设备数据服务
/// 
/// 负责设备数据的缓存、获取和管理
class DeviceService extends GetxService {
  // 设备数据缓存
  final RxList<Device> cachedDevices = <Device>[].obs;
  
  // 设备统计数据
  final RxInt totalDeviceCount = 0.obs;
  final RxInt onlineCount = 0.obs;
  final RxInt offlineCount = 0.obs;
  final RxInt inactiveCount = 0.obs;
  final RxInt disabledCount = 0.obs;
  
  // 数据是否已加载的标志
  final RxBool isDataLoaded = false.obs;
  
  // 最后加载时间
  Rx<DateTime?> lastLoadTime = Rx<DateTime?>(null);

  // 缓存有效期 (分钟)
  final int cacheValidityMinutes = 15;

  // Repository实例
  late final DeviceRepository _deviceRepository;

  @override
  void onInit() {
    super.onInit();
    _deviceRepository = Get.find<DeviceRepository>();
    debugPrint('DeviceService 已初始化');
  }

  /// 获取所有设备列表数据
  /// 如果有缓存且在有效期内，直接返回缓存
  /// 否则从服务器加载数据并更新缓存
  Future<List<Device>> getAllDevices({bool forceRefresh = false}) async {
    // 检查缓存是否有效
    if (!forceRefresh && isDataLoaded.value && _isCacheValid()) {
      debugPrint('DeviceService: 使用缓存数据，共${cachedDevices.length}条记录');
      return cachedDevices;
    }

    try {
      debugPrint('DeviceService: 从服务器加载设备数据');
      // 获取总设备数量（通过获取第一页设备列表的total字段）
      final response = await _deviceRepository.getDeviceList(pageNum: 1, pageSize: 1);
      final deviceCount = response.total;
      totalDeviceCount.value = deviceCount;
      
      // 如果设备数量为0，直接返回空列表
      if (deviceCount == 0) {
        cachedDevices.clear();
        isDataLoaded.value = true;
        lastLoadTime.value = DateTime.now();
        return [];
      }
      
      // 获取所有设备数据，限制最大数量为200，防止数据量过大
      final maxCount = deviceCount > 200 ? 200 : deviceCount;
      final fullResponse = await _deviceRepository.getDeviceList(
        pageNum: 1, 
        pageSize: maxCount
      );
      
      // 更新缓存
      cachedDevices.value = fullResponse.rows;
      isDataLoaded.value = true;
      lastLoadTime.value = DateTime.now();
      
      // 计算各状态设备数量
      _calculateDeviceStatusCounts();
      
      return fullResponse.rows;
    } catch (e) {
      debugPrint('DeviceService: 加载设备数据失败: $e');
      // 如果有缓存数据，返回缓存数据
      if (cachedDevices.isNotEmpty) {
        return cachedDevices;
      }
      rethrow;
    }
  }
  
  /// 根据设备缓存数据计算各状态设备数量
  void _calculateDeviceStatusCounts() {
    int online = 0;
    int offline = 0;
    int inactive = 0;
    int disabled = 0;
    
    for (final device in cachedDevices) {
      switch (device.status) {
        case 1: // 在线
          online++;
          break;
        case 2: // 离线
          offline++;
          break;
        case 0: // 未激活
          inactive++;
          break;
        case 3: // 禁用
          disabled++;
          break;
      }
    }
    
    onlineCount.value = online;
    offlineCount.value = offline;
    inactiveCount.value = inactive;
    disabledCount.value = disabled;
  }

  /// 获取设备状态统计
  Future<void> getDeviceStatusCounts({bool forceRefresh = false}) async {
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      // 如果缓存无效或强制刷新，先获取最新数据
      await getAllDevices(forceRefresh: forceRefresh);
      return;
    }
    
    // 如果缓存有效，直接使用缓存的计数
    debugPrint('DeviceService: 使用缓存的设备状态统计');
  }

  /// 获取主页所需的设备统计数据
  Future<Map<String, int>> getHomeStatistics({bool forceRefresh = false}) async {
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      await getAllDevices(forceRefresh: forceRefresh);
    }
    
    return {
      'totalCount': totalDeviceCount.value,
      'onlineCount': onlineCount.value, 
      'offlineCount': offlineCount.value,
      'inactiveCount': inactiveCount.value,
      'disabledCount': disabledCount.value,
    };
  }
  
  /// 根据设备ID获取设备详情
  /// 优先从缓存中查找，如果缓存中没有，则从服务器获取
  Future<Device?> getDeviceById(int deviceId) async {
    // 尝试从缓存中查找
    if (isDataLoaded.value && _isCacheValid()) {
      final device = cachedDevices.firstWhereOrNull((d) => d.deviceId == deviceId);
      if (device != null) {
        return device;
      }
    }
    
    // 缓存中没有，尝试重新加载所有设备
    if (!isDataLoaded.value || !_isCacheValid()) {
      await getAllDevices();
      final device = cachedDevices.firstWhereOrNull((d) => d.deviceId == deviceId);
      if (device != null) {
        return device;
      }
    }
    
    // 仍然没有找到，直接从服务器获取该设备
    try {
      final response = await _deviceRepository.getDeviceDetail(deviceId);
      if (response.data != null) {
        return response.data;
      }
      return null;
    } catch (e) {
      debugPrint('DeviceService: 获取设备详情失败: $e');
      return null;
    }
  }
  
  /// 根据产品ID获取该产品下的所有设备
  Future<List<Device>> getDevicesByProductId(int productId, {bool forceRefresh = false}) async {
    // 确保设备数据已加载
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      await getAllDevices(forceRefresh: forceRefresh);
    }
    
    // 从缓存中筛选该产品下的设备
    return cachedDevices.where((device) => device.productId == productId).toList();
  }
  
  /// 清除缓存
  void clearCache() {
    cachedDevices.clear();
    isDataLoaded.value = false;
    lastLoadTime.value = null;
    totalDeviceCount.value = 0;
    onlineCount.value = 0;
    offlineCount.value = 0;
    inactiveCount.value = 0;
    disabledCount.value = 0;
    debugPrint('DeviceService: 缓存已清除');
  }
  
  /// 检查缓存是否在有效期内
  bool _isCacheValid() {
    if (lastLoadTime.value == null) return false;
    
    final now = DateTime.now();
    final duration = now.difference(lastLoadTime.value!);
    return duration.inMinutes < cacheValidityMinutes;
  }
} 